package com.sendi.system.action;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sendi.system.bean.ApplicationContextHelper;
import com.sendi.system.bean.PushHelper;
import com.sendi.system.bean.SysLogHelper;
import com.sendi.system.service.ServiceSupportImp;
import com.sendi.system.util.common.ObjectSorter;

public class SysAction extends ActionSupport {
	/////////////start 从0 开始
	public String start;
	public String limit;
	public String _dc;
	public String dir;
	public String sort;
	public String   data_session_name;
	public String x;
	public String y;
	 
	public ServiceSupportImp serviceSupportImp;
	
    public String Treetext;	
	public int Treeid;
    public boolean Treeleaf=false;
    public String deleterecord;
    public DataSource dataSource;
    public ApplicationContextHelper applicationContextHelper;
    /*
     * 系统日志记录接口
     */
    public SysLogHelper sysLogHelper;
    /*
     * 消息推送接口
     */
    public PushHelper pushHelper;
    public String node;
 
    /*
     * 对像类型的集合进行排序
     */
    public void sortObjectList(List datas)
    {
    	//数据不为空，且大小大于1才进行排序
    	if(datas!=null&&datas.size()>1&&this.sort!=null&&this.dir!=null)
    	{
    		ObjectSorter s=new ObjectSorter(this.sort,this.dir);
    		Collections.sort(datas, s);//List 数据源进行排序
    	}
    }
	public HttpSession getSession()
	{
		
		return getRequest().getSession();
	}
    public void addDataToSession()
    {
    	
    }
	public String getUserName()
	{
		return getSession().getAttribute("userName").toString();
		
	}
	public String getSessionID()
	{
		try
		{
			return getSession().getId();
		}
		catch (Exception e) {
		 
		}
		return null;
 	}
	/*
	 * 获取系统所处的阶段 
	 */
	protected String getSystephase()
	{
		String re="develop";
		try
		{
			HashMap<String,String> sysconfigpara =(HashMap<String,String> )applicationContextHelper.servletContext.getAttribute("sendi_sys_config_para");
			re=sysconfigpara.get("sendi_system_phase");
		}
		catch (Exception e) {
			 
		}
	
		return re;
	}
 
	public List getListData(String hql)
	{
		  return this.serviceSupportImp.findByHQL(hql);
	}
	public void updata(Object obj,Session session)
	{
		session.update(obj);
	}
	public Session getHibernateSession()
	{
		return this.serviceSupportImp.getDao().getSessionFactory().openSession();
	}
	public List getListData(String hql,Session session)
	{
		return session.createQuery(hql).list();
	}
	public String getUserId()
	{
		return getSession().getAttribute("userid").toString();
	}
	public String getUserKeyId()
	{
		return getSession().getAttribute("user_id").toString();
		
	}
	public HttpServletRequest getRequest(){
		ActionContext ctx = ActionContext.getContext();        
		HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);        
		return request;
	}
	
	public HttpServletResponse getResponse(){
		ActionContext ctx = ActionContext.getContext();        
		HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);
		return response;
	}
	public ServletContext getServletContext()
	{
		 return applicationContextHelper.servletContext;
		
	}
 
	public Connection getConnection()
	{
		try {
			return  this.dataSource.getConnection();
		} catch (SQLException e) {
			 
			e.printStackTrace();
		}
		return null;
	}
	public ResultSet excuteQuery(String sql)
	{
		Connection con=this.getConnection();
		if(con!=null)
		{
			try {
				return con.createStatement().executeQuery(sql);
			} catch (SQLException e) {
				 
				e.printStackTrace();
				return null;
			}
		}
		else
		{
			return null;
		}
	}
	
	public int excuteUpdate(String sql)
	{
		Connection con=this.getConnection();
		if(con!=null)
		{
			try {
				return con.createStatement().executeUpdate(sql);
			} catch (SQLException e) {
				 
				e.printStackTrace();
				return -1;
			}
		}
		else
		{
			return -1;
		}
	}
	
	
	
	public void excuteBatchDelete(String[] sql)
	{
		Connection conn=this.getConnection();
		Statement state=null;
		if(conn!=null)
		{
			try {
				state=conn.createStatement();
				for(String i:sql)
				{
					state.addBatch(i);
				}
				state.executeBatch();
				System.out.println("Exceute batch success...");
			} catch (SQLException e) {
			 
				e.printStackTrace();
			}
			finally
			{
				try {
					conn.close();
				} catch (SQLException e) {
				 
					e.printStackTrace();
				}
			}
			
		}
		else
		{
			System.out.println("删除操作出错，无法获取数据库连接");
		}
		
	}
	public void writeJSONObject(Object obj){
		try
		{
			HttpServletResponse response = getResponse();
	        response.setContentType("text/html");
	        response.setCharacterEncoding("UTF-8");
	     
	        System.out.println( JSONObject.fromObject(obj).toString());
	         response.getWriter().print(JSONObject.fromObject(obj).toString());

		}catch (Exception e) {
			  e.printStackTrace();
		}
	
	}
	public void writeJSONArray(List array){
		
		try
		{
			this.sortObjectList(array);			
			HttpServletResponse response = getResponse();
	        response.setContentType("text/html");
	        response.setCharacterEncoding("UTF-8");
	        List<Object> pagedata=new ArrayList<Object>();
	        
	        int starti=Integer.parseInt(this.start);
	        int limiti=Integer.parseInt(this.limit);
	        System.out.println("list data size"+array.size());
	        if((starti+limiti+1)>array.size())
	        {
	        	pagedata.addAll(array.subList(starti,array.size()));
	        }
	        else
	        {
	        	pagedata.addAll(array.subList(starti, starti+limiti));
	         
	        }
	        String jsons = JSONArray.fromObject(pagedata).toString();
	       
	       String res="{totalCount:"+array.size()+",data:"+jsons+"}";
	       System.out.println(res);
	       response.getWriter().print(res);
		}
		catch (Exception e) {
			 e.printStackTrace();
		}
	 
	}
 
	public void writeResponseText(String responseText){
		try
		{
			HttpServletResponse response = getResponse();
	        response.setContentType("text/html");
	        response.setCharacterEncoding("UTF-8");
	        response.getWriter().print(responseText);
		}
		catch (Exception e) {
			 e.printStackTrace();
		}
		
	}
	
	public String iso2utf8(String o)
	{
		if(o==null||o.toString().length()==0)
		{
			return "";
		}
		else
		{
			try {
				return new String(o.getBytes("ISO-8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				 
				e.printStackTrace();
			}
			return "";
		}
	}
	
	public String getStart() {
		return start;
	}
	public void setStart(String start) {
		this.start = start;
	}
	public String getLimit() {
		return limit;
	}
	public void setLimit(String limit) {
		this.limit = limit;
	}
	public String get_dc() {
		return _dc;
	}
	public void set_dc(String _dc) {
		this._dc = _dc;
	}
	public String getDir() {
		return dir;
	}
	public void setDir(String dir) {
		this.dir = dir;
	}
	public String getSort() {
		return sort;
	}
	public void setSort(String sort) {
		this.sort = sort;
	}
	public ServiceSupportImp getServiceSupportImp() {
		return serviceSupportImp;
	}
	public void setServiceSupportImp(ServiceSupportImp serviceSupportImp) {
		this.serviceSupportImp = serviceSupportImp;
	}

	public String getData_session_name() {
		return data_session_name;
	}

	public void setData_session_name(String data_session_name) {
		this.data_session_name = data_session_name;
	}

	public String getTreetext() {
		return Treetext;
	}

	public void setTreetext(String treetext) {
		Treetext = treetext;
	}

	public int getTreeid() {
		return Treeid;
	}

	public void setTreeid(int treeid) {
		Treeid = treeid;
	}

	public boolean isTreeleaf() {
		return Treeleaf;
	}

	public void setTreeleaf(boolean treeleaf) {
		Treeleaf = treeleaf;
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public String getDeleterecord() {
		return deleterecord;
	}

	public void setDeleterecord(String deleterecord) {
		this.deleterecord = deleterecord;
	}

	public ApplicationContextHelper getApplicationContextHelper() {
		return applicationContextHelper;
	}

	public void setApplicationContextHelper(
			ApplicationContextHelper applicationContextHelper) {
		this.applicationContextHelper = applicationContextHelper;
	}

	public SysLogHelper getSysLogHelper() {
		return sysLogHelper;
	}

	public void setSysLogHelper(SysLogHelper sysLogHelper) {
		this.sysLogHelper = sysLogHelper;
	}

	public String getX() {
		return x;
	}

	public void setX(String x) {
		this.x = x;
	}

	public String getY() {
		return y;
	}

	public void setY(String y) {
		this.y = y;
	}

	public PushHelper getPushHelper() {
		return pushHelper;
	}

	public void setPushHelper(PushHelper pushHelper) {
		this.pushHelper = pushHelper;
	}
	public String getNode() {
		return node;
	}
	public void setNode(String node) {
		this.node = node;
	}
  
}
